package com.ruoyi.finance.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.finance.domain.TVoucher;
import com.ruoyi.finance.service.ITVoucherService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 凭证管理Controller
 * 
 * @author ruoyi
 * @date 2025-02-27
 */
@RestController
@RequestMapping("/voucher")
@Slf4j
public class TVoucherController extends BaseController
{
    @Autowired
    private ITVoucherService tVoucherService;

    /**
     * 查询凭证管理列表
     */
    @RequiresPermissions("finance:voucher:list")
    @GetMapping("/list")
    public TableDataInfo list(TVoucher tVoucher)
    {
        startPage();
        List<TVoucher> list = tVoucherService.selectTVoucherList(tVoucher);
        return getDataTable(list);
    }

    /**
     * 导出凭证管理列表
     */
    @RequiresPermissions("finance:voucher:export")
    @Log(title = "凭证管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TVoucher tVoucher)
    {
        List<TVoucher> list = tVoucherService.selectTVoucherList(tVoucher);
        ExcelUtil<TVoucher> util = new ExcelUtil<TVoucher>(TVoucher.class);
        util.exportExcel(response, list, "凭证管理数据");
    }

    /**
     * 获取凭证管理详细信息
     */
    @RequiresPermissions("finance:voucher:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tVoucherService.selectTVoucherById(id));
    }

    /**
     * 新增凭证管理
     */
    @RequiresPermissions("finance:voucher:add")
    @Log(title = "凭证管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TVoucher tVoucher)
    {
        return toAjax(tVoucherService.insertTVoucher(tVoucher));
    }

    /**
     * 修改凭证管理
     */
    @RequiresPermissions("finance:voucher:edit")
    @Log(title = "凭证管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TVoucher tVoucher)
    {
        return toAjax(tVoucherService.updateTVoucher(tVoucher));
    }

    /**
     * 删除凭证管理
     */
    @RequiresPermissions("finance:voucher:remove")
    @Log(title = "凭证管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tVoucherService.deleteTVoucherByIds(ids));
    }


    // 定义文件保存的基础目录为用户主目录下的 uploads 文件夹
    private static final String BASE_UPLOAD_DIR = System.getProperty("user.home") + "/uploads";

    @PostMapping("/uploadMultiple")
    public R uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        List<Map<String, Object>> fileInfoList = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            try {
                // 处理文件名，添加时间戳避免冲突
                String originalFileName = file.getOriginalFilename();
                String fileName = generateUniqueFileName(originalFileName);
                String filePath = BASE_UPLOAD_DIR + File.separator + fileName;
                File dest = new File(filePath);

                // 确保父目录存在
                if (!dest.getParentFile().exists()) {
                    if (!dest.getParentFile().mkdirs()) {
                        logger.error("无法创建父目录: {}", dest.getParentFile().getAbsolutePath());
                        return R.fail("文件上传失败：无法创建父目录");
                    }
                }

                // 保存文件
                file.transferTo(dest);

                // 收集文件信息
                Map<String, Object> fileInfo = new HashMap<>();
                fileInfo.put("originalFileName", originalFileName);
                fileInfo.put("fileName", fileName);
                fileInfo.put("filePath", filePath);
                fileInfo.put("fileSize", file.getSize());
                fileInfoList.add(fileInfo);


            } catch (IOException e) {
                logger.error("文件上传失败", e);
                return R.fail("文件上传失败：" + e.getMessage());
            }
        }
        if (fileInfoList.isEmpty()) {
            return R.fail("请选择要上传的文件");
        }
        return R.ok(fileInfoList,"文件上传成功");
    }
    // 生成唯一文件名的方法
    private String generateUniqueFileName(String originalFileName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        return timestamp + fileExtension;
    }

}
